<template>
  <div class="his-main">
    <el-row :gutter="10">
      <el-col :xs="24" :sm="18">
        <el-card>
          <h1>{{ historyDetail.title }} 时间：{{ historyDetail.date }}</h1>
          <el-image v-if="historyDetail.picUrl" :src="historyDetail.picUrl"></el-image>
          <pre class="his-content">{{ historyDetail.content }}</pre>
        </el-card>
      </el-col>
      <el-col :xs="0" :sm="6">
        <el-card class="contact-info">
          <h1>今日头条</h1>
          <div
            v-for="history in historyList"
            :key="history.id"
            @click="toHistoryDetail(history.id)"
          >
            <p>{{ history.date }}: {{ history.title }}</p>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { getHistoryDetail, getHistoryList } from "@/api/blog";
import { ElNotification } from "element-plus";
import { onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
interface History {
  content: string;
  picUrl: string;
  id: number;
  title: string;
  day: string;
  date: string;
  createDate: string;
}
const router = useRouter();
const route = useRoute();
const historyList = ref([]);
const historyDetail = ref<History>({
  content: "",
  picUrl: "",
  id: null,
  title: "",
  day: "",
  date: "",
  createDate: "",
});
const getAllHistory = async () => {
  try {
    const res: any = await getHistoryList();
    if (res?.status === 200) {
      historyList.value = res?.data || [];
    }
  } catch (error) {
    ElNotification.error({
      title: "Failed",
      message: "出错了：" + error.message,
      offset: 100,
    });
  }
};
const toHistoryDetail = async (id: number) => {
  try {
    const res: any = await getHistoryDetail(id);
    if (res?.status === 200) {
      historyDetail.value = res.data;
    }
  } catch (error) {
    ElNotification.error({
      title: "Failed",
      message: "出错了：" + error.message,
      offset: 100,
    });
  }
};
onMounted(async() => {
  await getAllHistory()
  toHistoryDetail(historyList.value[0].id)
})
watch(
  () => route,
  (newValue: any) => {
    if (newValue.path == "/history" && newValue.query.id) {
      toHistoryDetail(newValue.query.id);
      getAllHistory();
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
</script>
<style lang="scss" scoped>
.his-main {
  margin: 0 auto;
  h1 {
    font-size: 1.2rem;
    font-weight: bold;
  }
}
.his-content {
  white-space: pre-wrap;
}
.contact-info {
}
@media screen and (min-width: 768px) {
  .his-main {
    max-width: 1080px;
    padding-top: 20px;
  }
}
</style>
